<?php namespace App\Admin\Access\User\Services;

use App\Core\Repository\Criterias\SortCriteria;
use App\Admin\Access\Role\Meta as RoleMeta;
use App\Admin\Access\Role\Repository as RoleRepository;
use App\Admin\Access\Role\Criterias\HasPermission;

trait RoleManage {
    
    //获取用户信息（包含角色）
	public function getWithRole(){
        $user = $this->repository->addCriteria($this->getIndexCriteria())->first();
		if(!$user){
			return $this->inputError('用户不存在');
		}
		//获取角色
        $roleRespository = new RoleRepository();
        $roleRespository->addCriterias([
            new HasPermission(),
            new SortCriteria('role_id')
        ]);
        $rolesRaw = $roleRespository->all('role_id', 'parent_id', 'sub_count', 'name');
        $roles = $roleRespository->getTree($rolesRaw);
        //响应
        return $this->success([
            'user' => $user,
			'roles' => $roles
        ]);
	}
    
    public function changeRole(){
        $user = $this->repository->addCriteria($this->getIndexCriteria())->first();
		if(!$user){
			return $this->inputError('用户不存在');
		}
        $this->setMeta(new RoleMeta, 'role');
        $roleRespository = new RoleRepository();
        $roleRespository->addCriterias([
            'per' => new HasPermission(),
            'index' => $this->getIndexCriteria('role')
        ]);
        $role = $roleRespository->first();
		if(!$role){
			return $this->inputError('角色不存在');
		}
        try {
            $this->repository->resetCriteria()->addCriteria($this->getIndexCriteria());
            $this->repository->update([
                'role_id' => $role->role_id
            ]);
            return $this->success();
		} catch (\Exception $ex) {
            return $this->sysError($ex);
		}
    }
}